package com.kk.framework.util;


import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Clob;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


//import com.lowagie.text.pdf.codec.Base64;

public class StringUtils {
	public static int parseInt(String str){
	    try {
	    	
	          return Integer.parseInt(str);
	    } catch (Exception ex) {
	        return 0;
	    }
	}
	public static int parseInt(Object obj){
	    try {
	    	
	          return Integer.parseInt(obj.toString());
	    } catch (Exception ex) {
	        return 0;
	    }
	}
	
	public static BigDecimal parseBigDecimal(Object obj){
		BigDecimal value = BigDecimal.ZERO;
		if(obj != null){
			if(obj instanceof BigDecimal){
				value = (BigDecimal)obj;
			}else {
				try {
					Double v = Double.valueOf(obj.toString());
					return BigDecimal.valueOf(v);
				} catch (Exception ex) {
					return BigDecimal.ZERO;
				}
			}
		}
		return value;
	}
	
	public static String toString(Object obj) {
		if (obj == null) {
			return "";
		}
		if (obj.getClass().getName().equals("java.lang.String")) {
			return toString((String) obj);
		}
		if (obj.getClass().getName().equals("java.lang.Integer")) {
			return toString((Integer) obj);
		}
		if (obj.getClass().getName().equals("java.lang.Long")) {
			return toString((Long) obj);
		}
		if (obj.getClass().getName().equals("java.sql.Date")) {
			return toString((Date) obj);
		}
		if (obj.getClass().getName().equals("java.util.Date")) {
			return toString((java.util.Date) obj);
		}
		if (obj.getClass().getName().equals("java.lang.Float")) {
			return toString((Float) obj);
		}
		if (obj.getClass().getName().equals("java.sql.Timestamp")) {
			return toString((Timestamp) obj);
		}
		if (obj.getClass().getName().equals("java.lang.Double")) {
			return toString((Double) obj);
		}

		return obj.toString();
	}

	public static String toString(int obj) {
		return String.valueOf(obj);
	}

	public static String toString(long obj) {
		return String.valueOf(obj);
	}

	public static String toString(double obj) {
		return String.valueOf(obj);
	}

	public static String toString(float obj) {
		return String.valueOf(obj);
	}

	public static String toString(boolean obj) {
		return String.valueOf(obj);
	}

	public static String toString(char obj) {
		return String.valueOf(obj);
	}

	private static String toString(String obj) {
		if (obj == null) {
			return "";
		}
		return obj;
	}

	private static String toString(Integer obj) {
		if (obj == null) {
			return "";
		}
		return obj.toString();
	}

	private static String toString(Long obj) {
		if (obj == null) {
			return "";
		}
		return obj.toString();
	}

	private static String toString(Date obj) {
		if (obj == null) {
			return "";
		}
		DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd");
		return df.format(obj);
	}

	private static String toString(Double obj) {
		if (obj == null) {
			return "";
		}
		return obj.toString();
	}

	private static String toString(Float obj) {
		if (obj == null) {
			return "";
		}
		return obj.toString();
	}

	private static String toString(Timestamp obj) {
		if (obj == null) {
			return "";
		}
		return obj.toString();
	}

	private static String toString(java.util.Date obj) {
		if (obj == null) {
			return "";
		}
		return getDateString(obj);
	}

	private static String getDateString(java.util.Date adate) {
		SimpleDateFormat df = null;
		String returnValue = "";

		if (adate != null) {
			df = new SimpleDateFormat("yyyy-MM-dd");
			returnValue = df.format(adate);
		}

		return (returnValue);
	}

	/**
	 * 在 source 后边填充 target 总长len (target 单字符)
	 * 
	 * @param source
	 * @param target
	 * @param len
	 * @return
	 */
	public static String fillAfter(String source, String target, int len) {
		StringBuffer bf = new StringBuffer(len);
		for (int i = 0; i < len; i++) {
			bf.append(target);
		}
		String temp = bf.toString();
		temp = temp.substring(source.length(), len);
		return source + temp;
	}

	/**
	 * 在 source 前边填充 target (target 单字符),填充完后总长度为len
	 * 
	 * @param source
	 * @param target
	 * @param len
	 * @return
	 */
	public static String fillBefore(String source, String target, int len) {
		StringBuffer bf = new StringBuffer(len);
		for (int i = 0; i < len; i++) {
			bf.append(target);
		}
		String temp = bf.toString();
		temp = temp.substring(0, len - source.length());
		return temp + source;
	}
	
	public static String tofirstUpperCase(String source,int index){
		String temp=source.substring(0,index);
		source=temp.toUpperCase()+source.substring(index,source.length());
		return source;
	}
	public static String tofirstLowerCase(String source,int index){
		String temp=source.substring(0,index);
		source=temp.toLowerCase()+source.substring(index,source.length());
		return source;
	}
	
	public static String and(String value,String target) {
			
		 BigInteger _value = new BigInteger(value, 2);
         BigInteger _target = new BigInteger(target, 2);
         
         return StringUtils.fillBefore(Integer.toBinaryString(_value.and(_target).intValue()), "0", value.length());
	}
	
	public static String or(String value,String target) {
		 BigInteger _value = new BigInteger(value, 2);
        BigInteger _target = new BigInteger(target, 2);
        return StringUtils.fillBefore(Integer.toBinaryString(_value.or(_target).intValue()), "0", value.length());
	}
	
	public static String round(double d, int n) {
        if (d == 0) {
            d = 0;
        }
        if (n < 0) {
            n = 0;
        }
        String str = "";
        if (n == 0) {
            str = "0";
        } else {
            str = "0.";
        }
        for (int i = 0; i < n; i++) {
            str = str + "0";
        }
        DecimalFormat formater = new DecimalFormat(str);
        BigDecimal b = new BigDecimal(d+"");
        double tempd = b.setScale(n, BigDecimal.ROUND_HALF_UP).doubleValue();


        if (tempd == 0) {
            tempd = 0;
        }
        return formater.format(tempd);
    }
	
	public static boolean isEquals(String str1,String str2){
		if(str1!=null&&str1.equals(str2)){
			return true;
		}else{
			return false;
		}
	}
	
	public static boolean isNotEmpty(String str){
		if(str!=null&&!str.isEmpty()){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 判断是否为数值字符串，支持负号，小学点及指数形式
	 * @param str 数值字符串
	 * @return
	 */
	public static boolean isNumeric(String str)
	{
		try{
		    Float.valueOf(str);
		    return true;
		}catch(Exception e){
		    return false;
		}
	}
	
	public static String date2String(java.util.Date date)
	{
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
	}
	
	public static String date2String(java.util.Date date,String format)
	{
		return new SimpleDateFormat(format).format(date);
	}
	
	/**
	 * 返回格林威治时间
	 * @param date
	 * @return String
	 */
	public static String date2StringGMT(java.util.Date date){
		TimeZone tz = TimeZone.getTimeZone("Etc/Greenwich");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		sdf.setTimeZone(tz);
		String result = sdf.format(date);
		return result;
	}
	
	public static boolean isEmpty(String str){
		return !isNotEmpty(str);
	}
	
	/**
	 * 将clob转化成string
	 * @param clob
	 * @return
	 */
	public static String clob2String(Clob clob){
		String result = "";
		if(clob!=null){
			try {
				result = clob.getSubString(1, (int)clob.length());
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
	/**
	 * base64解密
	 * @param key
	 * @return
	 */
	public static String base64decode(String key){
		String result = "";
		/*if(isNotEmpty(key))
			result = new String(Base64.decode(key));   */
		return result;
	}
	
	/**
	 * base64加密
	 * @param value
	 * @return
	 */
	public static String base64encode(String value){
		String result = "";
		/*if(isNotEmpty(value)){
			result= new String(Base64.encodeBytes(value.getBytes()));
			result = result.replaceAll("\\n", "");
		}  */
		return result;
	}
	/**
	 * 日期格式字符串转化为日期对象
	 * yyyy-MM-dd HH:mm:ss
	 * 
	 * @param date
	 * @return
	 */
	public static java.util.Date string2Date(String date){
		java.util.Date result = null;
		try {
			if(isNotEmpty(date)){
				result = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 日期格式字符串转化为日期对象,format为日期格式
	 *
	 * @param date
	 * @param format
	 * @return
	 */
	public static java.util.Date string2Date(String date,String format){
		java.util.Date result = null;
		try {
			if(isNotEmpty(date)){
				result = new SimpleDateFormat(format).parse(date);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 将string数组转化成带间隔的字符串
	 * 
	 * @param array
	 * @param space
	 * @return
	 */
	public static String array2StringWithSpace(String[] array, String space){
		String result = "";
		if (array == null || array.length == 0)
			return result;
		for (String item : array) {
			String string = item==null?"":item;
			if (!string.isEmpty())
				result += string + space;
		}
		if (result.isEmpty()) {
			return result;
		}
		return result.substring(0, result.length() - space.length());
	}
	/**
	 * 将string集合转化成带间隔的字符串
	 * 
	 * @param list
	 * @param space
	 * @return
	 */
	public static String list2StringWithSpace(Collection<?> list ,String space){
		String result = "";
		if (list == null || list.isEmpty())
			return result;
		for (Object item : list) {
			String string = item==null?"":item.toString();
			if (!string.isEmpty())
				result += string + space;
		}
		if (result.isEmpty()) {
			return result;
		}
		return result.substring(0, result.length() - space.length());
	}
	/**
	 * 将str用space分割,返回list集合
	 * 
	 * @param str
	 * @param space
	 * @return List<String>
	 */
	public static List<String> string2ListWithSpace(String str ,String space){
		List<String> result = new ArrayList<String>();
		if(isEmpty(str)){
			return result;
		}
		String[] strs = str.split(space);
		result = Arrays.asList(strs);
		return result;
	}
	
	/**
	 * String类型替换source的第num位为to
	 * num从0开始
	 * @param source
	 * @param to
	 * @param num
	 * @return
	 */
	public static String replaceStrByNum(String source,String to,Integer num){
		if(isEmpty(source)||to==null||num==null||num>=source.length()) return null;
		String temp = source.charAt(num)+"";
		if(!temp.equals(to)){
			String head = source.substring(0,num);
			String foot = source.substring(num+1);
			source = head + to + foot;
		}
		return source;
	}
	
	/**
	 * StringBuilder类型替换source的第num位为to
	 * num从0开始
	 * @param source
	 * @param to
	 * @param num
	 * @return
	 */
	public static StringBuilder replaceStrByNum(StringBuilder source,String to,Integer num){
		if(source==null||source.length()==0||to==null||num==null||num>=source.length()) return null;
		String temp = source.charAt(num)+"";
		if(!temp.equals(to)){
			String head = source.substring(0,num);
			String foot = source.substring(num+1);
			source = source.delete(0, source.length());
			source = source.append(head).append(to).append(foot);
		}
		return source;
	}	
	
	/**
	 * 拼接stirng
	 * @param objects
	 * @return
	 */
    public static String join(Object... objects) {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < objects.length; i++) {
            buffer.append(objects[i]);
        }
        return buffer.toString();
    }
    
    /***
     * 获取属性名第一级对象名称，如（Account.Name得到Account，Account.Owner.Name得到Account）
     * 
     * @param attrName
     * @return
     */
	public static String firstName(String attrName) 
	{
		int i = attrName.indexOf(".");
		if(i > 0) {
			return attrName.substring(0, i);
		} else {
			return attrName;
		}
	}
	
	/**
     * 获取属性名
     * 
     * @param attrName
     * @return
     */
	public static String lastName(String attrName) 
	{
		int i = attrName.lastIndexOf(".");
		if(i > 0) {
			return attrName.substring(i+1);
		} else {
			return attrName;
		}
	}
	
	/**
	 * 根据attrName获取entityType
	 * 
	 * @param attrName
	 * @return
	 */
	public static String name2cname(String attrName) {
		int pos = attrName.indexOf(".");
		if(pos == -1)
			return "";
		String str = attrName.substring(pos+1);
		return str;
	}
	
	/**
	 * 取属性名的父对象属性名(即取最后一个点之前的部分)
	 *
	 * @param  name 属性名
	 * @return string 返回父对象属性名
	 */
	public static String name2pname(String name){
		int pos =name.lastIndexOf(".");
		if(pos==-1){
			return "";
		}
		String str = name.substring(0, pos);
		return str;
	}
	
	/**
	 * 将字符串重复指定的次数 ，并返回。如 repeat("aa",2) 将返回aaaa
	 * 
	 * @param string
	 * @param i
	 * @return
	 */
	public static String repeat(String string, int i) {
		StringBuffer stringBuffer = new StringBuffer();
		while (i > 0) {
			stringBuffer.append(string);
			i--;
		}
		return stringBuffer.toString();
	}
	
	/**
	 * 将map的tostring字符串转化成map
	 * 
	 * @param str
	 * @return
	 */
	public static Map<String, String> string2Map(String str){
		if (isEmpty(str)) {
			return null;
		}
		Map<String, String> result = new HashMap<String, String>();
		str = str.replaceAll("\\{", "");
		str = str.replaceAll("\\}", "");
		String[] strs = str.split(", ");
		for (String string : strs) {
			String key = string.split("=")[0];
			String value = "";
			if (string.split("=").length != 1) {
				value = string.split("=")[1];
			}
			result.put(key, value);
		}
		return result;
	}
	
	/**
	 * 转义特殊字符
	 * 
	 * @param str
	 * @return
	 */
	public static String escapeString(String str){
		if(isNotEmpty(str)){
			if(str.contains("$")){
				str = str.replace("$", "\\$");
			}
		}
		return str;
	}
	
	/**
	 * 根据string返回boolean,如是true则返回true,其它的false
	 * 
	 * @param str
	 * @return
	 */
	public static Boolean string2Boolean(String str){
		if(isNotEmpty(str)){
			if(str.equals("true")){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 将字符串转换为KV数组,形如: a:b;c:d
	 * 
	 * @param str
	 * @param split1
	 * @param split2
	 * @return Map<String, String>
	 */
	public static Map<String, String> string2MapWithSplit(String str,String split1,String split2){
		if(isEmpty(str)){
			return null;
		}
		if(isEmpty(split1)){
			split1 = ";";
		}
		if(isEmpty(split2)){
			split2 = "=";
		}
		Map<String, String> result = new HashMap<String, String>();
		String[] strs = str.split(split1);
		for (String string : strs) {
			String[] tmpStrs = string.split(split2);
			result.put(tmpStrs[0], tmpStrs[1]);
		}
		return result;
	}
	
	/**
	 * 获取字符串中的字母和数字,以空格和汉字为分割负,返回list
	 * 
	 * @param str
	 * @return
	 */
	public static List<String> getLetterAndNums(String str){
		List<String> result = new ArrayList<String>();
		if(isEmpty(str)) return result;
        String s = "\\d+.\\d+|\\w+";
        Pattern pattern=Pattern.compile(s);  
        Matcher ma=pattern.matcher(str);  
        while(ma.find()){  
        	result.add(ma.group());
        }  
        return result;
	}
	
	/**
	 * 将字符串非中文去掉
	 * 
	 * @param str
	 * @return
	 */
	public static String strWithChinese(String str){
		if(isEmpty(str)){
			return "";
		}
		return str.replaceAll("[^\\u4e00-\\u9fa5]", "");
	}
	
	public static int compare(String str, String target) {
		int d[][]; // 矩阵
		int n = str.length();
		int m = target.length();
		int i; // 遍历str的
		int j; // 遍历target的
		char ch1; // str的
		char ch2; // target的
		int temp; // 记录相同字符,在某个矩阵位置值的增量,不是0就是1
		if (n == 0) {
			return m;
		}
		if (m == 0) {
			return n;
		}
		d = new int[n + 1][m + 1];
		for (i = 0; i <= n; i++) { // 初始化第一列
			d[i][0] = i;
		}

		for (j = 0; j <= m; j++) { // 初始化第一行
			d[0][j] = j;
		}

		for (i = 1; i <= n; i++) { // 遍历str
			ch1 = str.charAt(i - 1);
			// 去匹配target
			for (j = 1; j <= m; j++) {
				ch2 = target.charAt(j - 1);
				if (ch1 == ch2 || ch1 == ch2 + 32 || ch1 + 32 == ch2) {
					temp = 0;
				} else {
					temp = 1;
				}
				// 左边+1,上边+1, 左上角+temp取最小
				d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + temp);
			}
		}
		return d[n][m];
	}

	private static int min(int one, int two, int three) {
		return (one = one < two ? one : two) < three ? one : three;
	}
	
	/**
	 * 去年字符串首尾的空格，如果字符串为null，返回null
	 * @param str
	 * @return
	 */
	public static String trim(String str){
		String value = null;
		if(str != null){
			value = str.trim();
		}
		return value;
	}
}
